package utils;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GoogleMapsAPI {
	
	private Document doc;
	private Node distance;
	private String sLatLongIni;
	private String sLatLongFinal;
	
	public GoogleMapsAPI(String sLatLongIni, String sLatLongFinal)
	{
		this.sLatLongIni = sLatLongIni;
		this.sLatLongFinal = sLatLongFinal;
		this.doc = getDocument();	
	    Node node1 = this.doc.getChildNodes().item(getNodeIndex(this.doc.getChildNodes(), "DirectionsResponse"));    
	    Node rote =  node1.getChildNodes().item(getNodeIndex(node1.getChildNodes(), "route"));
	    Node leg =  rote.getChildNodes().item(getNodeIndex(rote.getChildNodes(), "leg"));
	    this.distance =  leg.getChildNodes().item(getNodeIndex(leg.getChildNodes(), "distance"));

		
	}
	
	public String getDistanceText () {

	    Node text =  this.distance.getChildNodes().item(getNodeIndex(distance.getChildNodes(), "text"));
	    return text.getTextContent();
	}

	public int getDistanceValue () {
	    Node text =  this.distance.getChildNodes().item(getNodeIndex(distance.getChildNodes(), "value"));
	    return Integer.parseInt(text.getTextContent());
	}

private int getNodeIndex(NodeList nl, String nodename) {
    for(int i = 0 ; i < nl.getLength() ; i++) {
        if(nl.item(i).getNodeName().equals(nodename))
            return i;
    }
    return -1;
}

private Document getDocument() {
    String url = "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin=" + this.sLatLongIni
            + "&destination=" + this.sLatLongFinal
            + "&sensor=false&units=metric&mode=driving";

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        return doc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
}
